package com.demo.controller;

/**
 * @author leiliang
 * @version 1.0
 * @Description  测试异步
 * @date 2020/11/11 11:56
 */

import com.demo.async.AsyncTask;
import com.demo.common.ResponseData;
import com.demo.service.AsyncService;
import lombok.extern.slf4j.Slf4j;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.concurrent.ExecutionException;
import java.util.concurrent.Future;

/**
 * @author qjwyss
 * @date 2018/10/12
 * @description
 */
@RestController
@Slf4j
public class ThreadController {


    @Autowired
    private AsyncService asyncService;


    @Autowired
    private AsyncTask asyncTask;



    @GetMapping("/hello")
    public String hello(){

        return "hello";
    }

    @GetMapping("/sss")
    public ResponseData<Void> sss(){

        //调用service层的任务
        asyncService.executeAsync();

        return ResponseData.success();
    }




    @GetMapping("/task")
    public void AsyncTaskTest() throws InterruptedException, ExecutionException {
        Future<String> task1 = asyncTask.doTask1();
        Future<String> task2 = asyncTask.doTask2();
        while(true) {
            if(task1.isDone() && task2.isDone()) {
                log.info("Task1 result: {}", task1.get());
                log.info("Task2 result: {}", task2.get());
                break;
            }
            Thread.sleep(1000);
        }
        log.info("All tasks finished.");
    }
}

